package com.chaodev.base.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

public class FileUtil {
    /**
     * 文件上传
     * @param request
     * @param files  获取到的文件MultipartFile
     * @param childrenPath 服务器存储路径相对于根路径
     * @param requestMap 存储文件路径（相对于服务器根路径,例：/upload/approval/1533715591534_test.text） 文件真实名字（例：test.txt）
     * @return
     */
    public static Boolean UploadFile(HttpServletRequest request, MultipartFile[] files, String childrenPath, Map<String, Object> requestMap) {
        if(files != null && files.length > 0) {
            String fileRealPath = null;//文件保存的完整路径
            String fileRealName = null;//文件名称
            File newFile = null;
            StringBuilder fjResult=new StringBuilder();
            for (MultipartFile file:files) {
                if(file.isEmpty()) {
                    continue;
                }
                fileRealName = file.getOriginalFilename();
                fileRealPath = childrenPath + System.currentTimeMillis() + "_" + fileRealName;
                String filepath = request.getServletContext().getRealPath("/").replaceAll("\\\\", "/") + fileRealPath;
                //String filepath=request.getSession().getServletContext().getRealPath("/");
                String basePath = request.getScheme()+"://"+request.getServerName()+":"+
                        request.getServerPort()+request.getContextPath()+"/"+fileRealPath;
                newFile = new File(filepath);
                //创建文件夹
                if(!newFile.getParentFile().exists()) {
                    newFile.getParentFile().mkdirs();
                }
                try {
                    file.transferTo(newFile);//保存文件
                    ////// System.out.println(fileRealPath);
                    fjResult.append(fjResult.toString().equals("")?"":",").append(fileRealName).append("|").append(filepath);
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
            requestMap.put("FJ_RESULT",fjResult);
            return true;
        }
        return false;
    }

    /**
     * 在上传文件前先检查是否有不允许的附件类型
     * @author dyl
     * @param files
     * @date 2019/6/17 9:03
     * @return boolean
     */
    public static boolean CheckFiles(MultipartFile[] files){
        String[] typeArr = new String[]{"jpg","png","gif","txt","pdf","docx","doc","xlsx","xls","zip","rar","ppt","pptx"}; //允许上传的附件类型
        ArrayList<String> typeList = new ArrayList<String>(Arrays.asList(typeArr));
        if(files != null && files.length > 0){
            String fileRealName = null;
            for(MultipartFile file:files){
                if(file.isEmpty()){
                    continue;
                }
                fileRealName = file.getOriginalFilename();
                String  filetype = fileRealName.substring(fileRealName.lastIndexOf(".")+1).toLowerCase(); //上传文件的后缀
                if(!typeList.contains(filetype)){
                    return false;
                }
            }
        }
        return true;
    }
}
